﻿#include "DataBaseMagr.h"
#include <QDebug>
#include <QSqlQuery>

DataBaseMagr *DataBaseMagr::self = NULL;

DataBaseMagr::DataBaseMagr(QObject *parent) : QObject(parent)
{
    
}

DataBaseMagr::~DataBaseMagr()
{
    if(m_buddyInfodb.isOpen())
    {
        m_buddyInfodb.close();
    }
    
    if(m_msgdb.isOpen())
    {
        m_msgdb.close();
    }
}

//打开好友数据库
bool DataBaseMagr::OpenBuddyInfoDb(const QString &dataName)
{
    m_buddyInfodb = QSqlDatabase::addDatabase("QSQLITE", "connectionUser");
    m_buddyInfodb.setDatabaseName(dataName);
    if (!m_buddyInfodb.open()) {
        qDebug() << "Open sql failed";
        return false;
    }

    // 添加数据表
    QSqlQuery query(m_buddyInfodb);

    // 创建我的好友表 id为好友id，userid为当前用户id
    query.exec("CREATE TABLE FRIEND (id INT, userId INT, name varchar(50))");

    // 创建群组表 id为群组id，userid为当前用户id
    query.exec("CREATE TABLE MYGROUP (id INT, userId INT, name varchar(50))");

    // 用户数据保存
    query.exec("CREATE TABLE USERINFO (id INT, name varchar(50), passwd varchar(50))");

    return true;
}

//打开聊天消息数据库
bool DataBaseMagr::OpenMessageDb(const QString &dataName)
{
    m_msgdb = QSqlDatabase::addDatabase("QSQLITE", "connectionMsg");
    m_msgdb.setDatabaseName(dataName);
    if (!m_msgdb.open()) {
        qDebug() << "Open sql failed";
        return false;
    }

    // 添加数据表
    QSqlQuery query(m_msgdb);
    // 创建历史聊天表
    query.exec("create table tb_BuddyMsg (id INTEGER PRIMARY KEY AUTOINCREMENT, "
                "uid INTEGER NOT NULL,"
                "time UNSIGNED BIG INT NOT NULL,"
                "sendflag INTEGER NOT NULL,"
                "font varchar(64) NOT NULL,"
                "content varchar(64) NOT NULL)");

    return true;
}

//添加历史聊天记录
void DataBaseMagr::AddHistoryMsg(const int &uid, int sendflag,const int& utctime,const QString& font,const QString& content)
{
    // 查询数据库
    QSqlQuery query("SELECT [id] FROM tb_BuddyMsg ORDER BY id DESC;", m_msgdb);
    int nId = 0;
    // 查询最高ID
    if (query.next()) {
        nId = query.value(0).toInt();
    }

    // 根据新ID重新创建用户
    query.prepare("INSERT INTO tb_BuddyMsg (uid, time, sendflag, font, content) "
                  "VALUES ( ?, ?, ?, ?, ?);");

    query.bindValue(0, uid);
    query.bindValue(1, utctime);
    query.bindValue(2, sendflag);
    query.bindValue(3, font);
    query.bindValue(4, content);

    query.exec();
}

/**
 * @brief DataBaseMagr::LoadHistoryMsg 查找和朋友uid的聊天记录，返回一个按时间降序排列的结果集
 * @param uid
 * @param count            count = -1,默认查询全部记录
 * @param offset            offset,偏移，即跳过最近的offset条聊天记录
 * @return
 */
QSqlQuery DataBaseMagr::LoadHistoryMsg(int uid, int offset, int count)
{
    QSqlQuery query(m_msgdb);
    if(count != -1)
    {
        query.exec(QString("SELECT * FROM tb_BuddyMsg WHERE uid= %1 ORDER BY id DESC LIMIT %2 OFFSET %3;").arg(uid).arg(count).arg(offset));
    }else
    {
        query.exec(QString("SELECT * FROM tb_BuddyMsg WHERE uid= %1 ORDER BY id ASC;").arg(uid));
    }
    return query;
}
